package com.hanbang.chu_xing_gao_zhao.view_find_esoterica;

import java.io.File;
import java.io.IOException;

import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.application.MyApplication;
import com.hanbang.chu_xing_gao_zhao.base.BaseDataActivity;
import com.hanbang.chu_xing_gao_zhao.myview.MorePopupWindowPublic_B;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog.MODE;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.view_public.SucceedHintActivity;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class FindEsotericaUploadingActivityD extends BaseDataActivity {
    /**
     * 图片展示
     */
    private ImageView picture;
    /**
     * 提示添加图片
     */
    private LinearLayout hintAddPicture;
    /**
     * 提示添加视频
     */
    private LinearLayout hintAddVideo;
    /**
     * 视频
     */
    private VideoView video;
    /**
     * 名称
     */
    private EditText name;
    /**
     * 特色
     */
    private EditText feature;
    /**
     * 底价
     */
    private EditText price;
    /**
     * 开始年
     */
    private EditText startYear;
    /**
     * 开始月
     */
    private EditText startMonth;
    /**
     * 开始日
     */
    private EditText startDay;
    /**
     * 结束年
     */
    private EditText endYear;
    /**
     * 结束月
     */
    private EditText endMonth;
    /**
     * 结束日
     */
    private EditText endDay;
    /**
     * 评价
     */
    private EditText comment;
    /**
     * 流程
     */
    private EditText process;
    /**
     * 声明
     */
    private EditText statement;
    /**
     * 众筹
     */
    private EditText zhongChou;
    /**
     * 提交
     */
    private TextView commit;
    /**
     * 菜系
     */
    private TextView styleOfCooking;
    /**
     * 图片路径
     */
    private String path = "";
    /**
     * 视频路径
     */
    private String pathVideo = "";
    /**
     * 菜系Id
     */
    private int styleOfCookingId = -1;
    /**
     * 控制播放
     */
    private MediaController mController;
    private File fileVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_uploading_d_activity);
        initView();
        setOnClickListener();
    }

    /**
     * 初始化view
     */
    private void initView() {
        setTitleMore(View.VISIBLE, View.INVISIBLE, "上传买断式秘籍", null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));

        // 控件初始化
        picture = (ImageView) findViewById(R.id.im_find_uploading_picture);
        hintAddPicture = (LinearLayout) findViewById(R.id.ll_find_uploading_hintAddPicture);
        hintAddVideo = (LinearLayout) findViewById(R.id.ll_find_uploading_hintAddVideo);
        video = (VideoView) findViewById(R.id.vv_find_uploading_video);
        name = (EditText) findViewById(R.id.et_find_uploading_name);
        feature = (EditText) findViewById(R.id.et_find_uploading_feature);
        price = (EditText) findViewById(R.id.et_find_uploading_diJia);
        startYear = (EditText) findViewById(R.id.et_find_uploading_startYear);
        startMonth = (EditText) findViewById(R.id.et_find_uploading_startMonth);
        startDay = (EditText) findViewById(R.id.et_find_uploading_startDay);
        endYear = (EditText) findViewById(R.id.et_find_uploading_endYear);
        endMonth = (EditText) findViewById(R.id.et_find_uploading_endMonth);
        endDay = (EditText) findViewById(R.id.et_find_uploading_endDay);
        comment = (EditText) findViewById(R.id.et_find_uploading_comment);
        process = (EditText) findViewById(R.id.et_find_uploading_process);
        statement = (EditText) findViewById(R.id.et_find_uploading_maiDuanShengMing);
        zhongChou = (EditText) findViewById(R.id.et_find_uploading_zhongChouMaiDuan);
        commit = (TextView) findViewById(R.id.tv_find_uploading_commit);
        styleOfCooking = (TextView) findViewById(R.id.tv_find_uploading_stylefCooking);

    }

    private void playVideo(String url) {
        // 控制视频播放
        mController = new MediaController(this);


        fileVideo = new File(pathVideo);

        if (fileVideo.exists()) {
            // 设置播放视频源的路径
            video.setVideoPath(fileVideo.getAbsolutePath());
            // 为VideoView指定MediaController
            video.setMediaController(mController);

            // 为MediaController指定控制的VideoView
            mController.setMediaPlayer(video);


            // 增加监听上一个和下一个的切换事件，默认这两个按钮是不显示的
            mController.setPrevNextListeners(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(FindEsotericaUploadingActivityD.this, "下一个", Toast.LENGTH_SHORT).show();
                }
            }, new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(FindEsotericaUploadingActivityD.this, "上一个", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        picture.setOnClickListener(onClickListener);
        hintAddPicture.setOnClickListener(onClickListener);
        hintAddVideo.setOnClickListener(onClickListener);
        video.setOnClickListener(onClickListener);
        commit.setOnClickListener(onClickListener);
        styleOfCooking.setOnClickListener(onClickListener);

    }

    /**
     * 处理监听
     */
    private OnClickListener onClickListener = new OnClickListener() {
        MorePopupWindowPublic_B popup;

        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                // 菜系
                case R.id.tv_find_uploading_stylefCooking:
                    popup = new MorePopupWindowPublic_B(FindEsotericaUploadingActivityD.this, styleOfCookingList, 8, 100);
                    popup.showPopupWindow(styleOfCooking, 0.5);

                    break;

                // 添加视频
                case R.id.ll_find_uploading_hintAddVideo:

                    // 新建一个dialog 对话框
                    MyDialog myDialogVideo = new MyDialog(FindEsotericaUploadingActivityD.this, R.style.about_me_dialog, MODE.HEAD);
                    // 添加图片的监听
                    myDialogVideo.setOnClickCallback(new com.hanbang.chu_xing_gao_zhao.myview.MyDialog.OnClickCallback() {

                        @Override
                        public void onClick(MyDialog dialog, Object number, Object content) {

                            // 录像
                            if ((Integer) number == 1) {
                                pathVideo = "";
                                File fDir = new File(MyApplication.picFilepath);
                                pathVideo = System.currentTimeMillis() + ".mp4";
                                if (fDir.exists() || fDir.mkdirs()) {
                                    File cameraFile = new File(fDir, pathVideo);
                                    if (!cameraFile.exists()) {
                                        try {
                                            cameraFile.createNewFile();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
                                    startActivityForResult(intent, 996);
                                }
                                // 相册选择
                            } else if ((Integer) number == 2) {
                                // 获取相册
                                Intent intent = new Intent();
                                intent.setType("video/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 997);
                            }

                        }
                    });
                    myDialogVideo.show();
                    break;
                // 提交
                /**
                 * type：类型，1为开放式，2为买断式
                 *
                 * title：秘籍名称
                 *
                 * tedian：特点
                 *
                 * price：价格，免费的传0
                 *
                 * cuisines_id：菜系，这个在效果图上没有体现出来，需要加上去的
                 *
                 * img_url:主图，秘籍效果图，一张">url:主图，秘籍效果图，一张
                 *
                 * shipin:视频，可选
                 *
                 * begin_date:开始时间，格式为2015-09-06
                 *
                 * end_date：结束时间，格式为2015-09-06
                 *
                 * pingjia：评价
                 *
                 * maiduanliucheng：买断流程
                 *
                 * maiduanshengming：买断声明
                 *
                 * huanyingzongchoumaiduan：欢迎众筹买断
                 */
                case R.id.tv_find_uploading_commit:
                    if (path.equals("")) {
                        MyToast.show(FindEsotericaUploadingActivityD.this, "图片不能为空", 1);
                        return;
                    } else if (name.getText().toString().equals("")) {
                        MyToast.show(FindEsotericaUploadingActivityD.this, "名称不能为空", 1);
                        return;
                    } else if (feature.getText().toString().equals("")) {
                        MyToast.show(FindEsotericaUploadingActivityD.this, "特色不能为空", 1);
                        return;
                    } else if (styleOfCookingId == -1) {
                        MyToast.show(FindEsotericaUploadingActivityD.this, "菜系不能为空", 1);
                        return;
                    } else if (comment.getText().toString().equals("")) {
                        MyToast.show(FindEsotericaUploadingActivityD.this, "评价不能为空", 1);
                        return;
                    } else if (process.getText().toString().equals("")) {
                        MyToast.show(FindEsotericaUploadingActivityD.this, "流程没有填写", 1);
                        return;
                    } else if (statement.getText().toString().equals("")) {
                        MyToast.show(FindEsotericaUploadingActivityD.this, "买断声明没有填写", 1);
                        return;
                    }

                    // 通过图片路径得到一个图片文件
                    File picture = new File(path);

                    RequestParams params = new RequestParams();
                    params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                            FindEsotericaUploadingActivityD.this, MySharedPreferences.USER_DATA, "tlephone"));
                    params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                            FindEsotericaUploadingActivityD.this, MySharedPreferences.USER_DATA, "password"));
                    params.addBodyParameter("type", 1 + "");
                    params.addBodyParameter("title", name.getText().toString());
                    params.addBodyParameter("tedian", feature.getText().toString());
                    params.addBodyParameter("price", price.getText().toString());
                    params.addBodyParameter("cuisines_id", styleOfCookingId + "");

                    params.addBodyParameter("img_url", picture);
                    params.addBodyParameter("shipin", fileVideo);

                    params.addBodyParameter("begin_date", startYear + "-" + startMonth + "-" + startDay);
                    params.addBodyParameter("end_date", endYear + "-" + endMonth + "-" + endDay);
                    params.addBodyParameter("pingjia", comment.getText().toString());
                    params.addBodyParameter("maiduanliucheng", process.getText().toString());
                    params.addBodyParameter("maiduanshengming", statement.getText().toString());
                    params.addBodyParameter("huanyingzongchoumaiduan", zhongChou.toString());

                    httpUploading(HttpInterfaces.Miji_Add, params);

                    break;
                // 添加图片
                case R.id.ll_find_uploading_hintAddPicture:
                    // 新建一个dialog 对话框
                    MyDialog myDialog = new MyDialog(FindEsotericaUploadingActivityD.this, R.style.about_me_dialog, MODE.HEAD);
                    // 添加图片的监听
                    myDialog.setOnClickCallback(new com.hanbang.chu_xing_gao_zhao.myview.MyDialog.OnClickCallback() {

                        @Override
                        public void onClick(MyDialog dialog, Object number, Object content) {

                            // 拍照
                            if ((Integer) number == 1) {
                                path = "";
                                File fDir = new File(MyApplication.picFilepath);
                                path = System.currentTimeMillis() + ".jpg";
                                if (fDir.exists() || fDir.mkdirs()) {
                                    File cameraFile = new File(fDir, path);
                                    if (!cameraFile.exists()) {
                                        try {
                                            cameraFile.createNewFile();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
                                    startActivityForResult(intent, 998);
                                }
                                // 相册选择
                            } else if ((Integer) number == 2) {
                                // 获取相册
                                Intent intent = new Intent();
                                intent.setType("image/*");

                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 999);
                            }

                        }
                    });
                    myDialog.show();
                    break;
                default:
                    break;
            }

            // 选择菜系 的回调
            if (popup != null) {

                popup.setOnClickCallback(new MorePopupWindowPublic_B.OnClickCallback() {
                    @Override
                    public void onClick(MorePopupWindowPublic_B morePopWindow, int id, String content, int type) {

                        if (type == 100) {
                            styleOfCooking.setText(content);
                            styleOfCookingId = id;
                            Toast.makeText(FindEsotericaUploadingActivityD.this, content, Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }

        }

    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        /**
         * 获取视频地址
         */
        if (requestCode == 997 && resultCode == -1) {
            Uri uri = data.getData();
            pathVideo = SystemTools.getPath(FindEsotericaUploadingActivityD.this, uri);
            MyLog.i("text", "*000**" + pathVideo);// *****
            // file = new File(pathVideo);
            hintAddVideo.setVisibility(View.GONE);
            playVideo(pathVideo);
            // 获取拍照的图片路径
        } else if (requestCode == 996 && resultCode == -1) {
            File fDir = new File(MyApplication.picFilepath);
            // 判断文件夹是否存在
            if (fDir.exists() || fDir.mkdirs()) {
                File cameraFile = new File(fDir, pathVideo);
                // 判断文件时是否存在
                if (cameraFile.exists()) {
                    pathVideo = cameraFile.getPath();
                    // file = new File(pathVideo);
                    hintAddVideo.setVisibility(View.GONE);
                    MyLog.i("text", "*111**" + pathVideo);// *****
                    playVideo(pathVideo);
                } else {
                    MyToast.show(FindEsotericaUploadingActivityD.this, "获取照片失败！", Toast.LENGTH_SHORT);
                }
            } else {
                MyToast.show(FindEsotericaUploadingActivityD.this, "获取照片失败！", Toast.LENGTH_SHORT);
            }
        }

        /**
         * 获取图片地址
         */
        if (requestCode == 999 && resultCode == -1) {
            Uri uri = data.getData();
            path = SystemTools.getPath(FindEsotericaUploadingActivityD.this, uri);
            bitmapUtils.display(picture, path);
            MyLog.i("text", "*BBBB**" + path);// *****
            hintAddPicture.setVisibility(View.GONE);
            // 获取拍照的图片路径
        } else if (requestCode == 998 && resultCode == -1) {
            File fDir = new File(MyApplication.picFilepath);
            // 判断文件夹是否存在
            if (fDir.exists() || fDir.mkdirs()) {
                File cameraFile = new File(fDir, path);
                // 判断文件时是否存在
                if (cameraFile.exists()) {
                    path = cameraFile.getPath();
                    MyLog.i("text", "*AAA**" + path);// *****
                    bitmapUtils.display(picture, path);
                    hintAddPicture.setVisibility(View.GONE);
                } else {
                    MyToast.show(FindEsotericaUploadingActivityD.this, "获取照片失败！", Toast.LENGTH_SHORT);
                }
            } else {
                MyToast.show(FindEsotericaUploadingActivityD.this, "获取照片失败！", Toast.LENGTH_SHORT);
            }
        }

    }

    ;

    /**
     * 提交上传秘籍
     */
    private void httpUploading(String url, RequestParams params) {
        httpUtils.send(HttpMethod.POST, url, params, new MyRequestCallBack<String>(this, "提交中...") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);

                    int result = json.getInt("Result");
                    MyLog.i("text", "111111***" + result + "***");
                    if (result == 0) {
                        MyLog.i("text", "22222***" + result + "***");
                        Intent intent = new Intent(FindEsotericaUploadingActivityD.this, SucceedHintActivity.class);
                        intent.putExtra("title", "提交成功");
                        intent.putExtra("contentHint", "感谢您的参与和分享\n我们将24小时审核完成");
                        startActivity(intent);
                        finish();
                    } else {
                        MyToast.show(FindEsotericaUploadingActivityD.this, "服务器忙，请稍后重试..", 1);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
}
